from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from app.db.session import get_db
from app.schemas.mcp_tool import MCPSubscription
from app.services.mcp_tool import MCPSubscriptionService

router = APIRouter()


@router.get("/", response_model=List[MCPSubscription])
def get_subscriptions(
    user_id: Optional[int] = None,
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """
    获取订阅列表，可选择指定用户ID
    """
    return MCPSubscriptionService.get_subscriptions(db, user_id=user_id, skip=skip, limit=limit)


@router.get("/{subscription_id}", response_model=MCPSubscription)
def get_subscription(subscription_id: int, db: Session = Depends(get_db)):
    """
    获取指定ID的订阅
    """
    return MCPSubscriptionService.get_subscription(db, subscription_id)


@router.post("/user/{user_id}/tool/{tool_id}", response_model=MCPSubscription)
def create_subscription(user_id: int, tool_id: int, db: Session = Depends(get_db)):
    """
    创建用户订阅
    """
    return MCPSubscriptionService.create_subscription(db, user_id, tool_id)


@router.delete("/user/{user_id}/tool/{tool_id}")
def cancel_subscription(user_id: int, tool_id: int, db: Session = Depends(get_db)):
    """
    取消用户订阅
    """
    MCPSubscriptionService.cancel_subscription(db, user_id, tool_id)
    return {"message": "订阅已取消"}


@router.get("/user/{user_id}/tool/{tool_id}", response_model=Optional[MCPSubscription])
def get_user_tool_subscription(user_id: int, tool_id: int, db: Session = Depends(get_db)):
    """
    获取用户对特定工具的订阅
    """
    subscription = MCPSubscriptionService.get_user_tool_subscription(db, user_id, tool_id)
    return subscription 